#include "MTTcpClient.h"

MTTcpClient::MTTcpClient(QObject *parent) : QObject(parent)
  , m_client(new QTcpSocket(this)) // QTcpSocket parent指向null时候不报错
{
    this->moveToThread(&m_clientThread);
    m_clientThread.start();

    connect(this, &MTTcpClient::sig_connnectToHost, this, &MTTcpClient::on_connectToHost);
    connect(m_client.get(), SIGNAL(connected()), this, SLOT(onClientConnected()));
    connect(m_client.get(), SIGNAL(disconnected()), this, SLOT(onClientDisconnected()));
    connect(m_client.get(), &QIODevice::readyRead, this, &MTTcpClient::onClientDataReady);
    connect(m_client.get(), SIGNAL(bytesWritten(qint64)), this, SLOT(onClientBytesWritten(qint64)));
    typedef void (QAbstractSocket::*QAbstractSocketErrorSignal)(QAbstractSocket::SocketError);
    connect(m_client.get(), static_cast<QAbstractSocketErrorSignal>(&QTcpSocket::error), this, &MTTcpClient::onClientError);

    qDebug() << "main thread:" << QThread::currentThread();
    qDebug() << "tracker thread:" << &m_clientThread;
}

MTTcpClient::~MTTcpClient()
{
    qDebug("MTTcpClient::~MTTcpClient()");
    m_client->close();

    // 停止线程
    m_clientThread.quit();
    m_clientThread.wait();
    qDebug("MTTcpClient::~MTTcpClient() end");
}

bool MTTcpClient::connectToHost(const QString &ip, qint64 port)
{
    emit sig_connnectToHost(ip, port);
    qDebug() << "MTTcpClient: connected to "<< ip<< ":" << port << " thread: " << QThread::currentThread();
    return true;
}

void MTTcpClient::disconnect()
{
    m_client->disconnectFromHost();
}

bool MTTcpClient::isConnected()
{
    if (m_client && m_client->state() == QAbstractSocket::ConnectedState) {
        return true;
    }
    return false;
}

bool MTTcpClient::on_connectToHost(const QString &ip, qint64 port)
{
    m_client->connectToHost(ip, quint16(port));
    if (!m_client->waitForConnected(1000)) {
        qDebug() << "MTTcpClient: It is time out to connect server: " << ip << ":" << port << " thread: " << QThread::currentThread();
        return false;
    }
    qDebug() << "MTTcpClient: connected to "<< ip<< ":" << port << " thread: " << QThread::currentThread();
    return true;
}

void MTTcpClient::onClientConnected()
{
    qDebug() << "TrackerClient is connected! thread:" << QThread::currentThread();
}

void MTTcpClient::onClientDisconnected()
{
    qDebug() <<"TrackerClient is disconnected! threadId:" << QThread::currentThread();
}

void MTTcpClient::onClientDataReady()
{
    /// 把点缓存到队列里面等待读取
    QByteArray data = m_client->readAll();
    qDebug() << "data:" << data << " hex:" << data.toHex() << " thread: " << QThread::currentThread();;
}

void MTTcpClient::onClientBytesWritten(qint64 bytes)
{
    qDebug() << "MTTcpClient Written " << bytes << " thread: " << QThread::currentThread();
}

void MTTcpClient::onClientError(QAbstractSocket::SocketError socketError)
{
    qDebug() << "客户端错误信息：" << socketError << " thread:" << QThread::currentThread();
}
